import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button, Modal, Form, Input, InputNumber, Message, Checkbox, Switch
} from '@arco-design/web-react';
import {  IconPlus, IconSearch } from '@arco-design/web-react/icon';
import useLocale from '@/utils/useLocale';
import styles from '@/pages/list/search-table/style/index.module.less';
import '@/pages/list/search-table/mock';
import locale from '@/pages/list/search-table/locale';
import api from '@/apis';
import getColumns from './constant';
function Subscription(props) {
  const t = useLocale(locale);
  const TextArea = Input.TextArea;

  const tableCallback = async (record, type) => {
    console.log(record, type);
    if (type === 'delete'){
      if (record.is_admin) {
        return Message.error("不可删除管理员")
      }
      Modal.confirm({
        title: '危险操作',
        content:
          '确认是否删除？',
        okButtonProps: {
          status: 'danger',
        },
        onOk: () => {
          api.delete('/api/v2/admin_emails/' + record.id).then((res) => {
            Message.info(res.data.message)
          }).catch(
            err => Message.error(err)
          ).finally(
            () => {
              fetchData()
            }
          )
        },
      });
    } else if (type === 'edit'){
      setIsEdit(true)
      setCurUser(record)
      setShowModal(true)
    }  else if (type === 'test'){
      setCurUser(record)
      setShowSendTempModal(true)
    } else{
      Message.error("功能暂未实现！")
    }
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true
  });
  const [loading, setLoading] = useState(true);

  const [showModal, setShowModal] = useState(false);
  const [showSendTempModal, setShowSendTempModal] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [formParams, setFormParams] = useState({});
  const [tempEmail, setTempEmail] = useState("");
  const [curUser, setCurUser] = useState({
    username: '',
    password: '',
    email: '',
    points: 0
  });
  const columns = useMemo(() => getColumns(tableCallback), [t]);
  const formRef = useRef()
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const sendTempEmail = (admin_email_id, send_to) => {
    api.post("/api/v1/admin/test_admin_email", {admin_email_id: admin_email_id, send_to: send_to}).then(res => {
      Message.info(res.data.message)
    }).catch(err => console.error(err))
  }
  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    setSelectedRowKeys(props.initChecks)
    api
      .get('/api/v2/admin_emails/', {
        params: {
          page: current,
          num: pageSize,
          ...formParams
        }
      })
      .then((res) => {
        setData(res.data.data);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.total
        });
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
    fetchData();
  }
  const handleSubmit = async () => {
    api.post('/api/v2/admin_emails/', formRef.current.getFields()).then((res) => {
      const status = res?.data.status
      if (status === 'success'){
        Message.success(res?.data.message)
        fetchData()
        setShowModal(false)
      }
    }).catch(err => {
      Message.error(err)
    })
  }

  const handleSubmitUpdate = async () => {
    api.put('/api/v2/admin_emails/' + curUser.id, formRef.current.getFields()).then((res) => {
      const status = res?.data.status
      if (status === 'success'){
        Message.success(res?.data.message)
        fetchData()
        setShowModal(false)
      }
    }).catch(err => {
      Message.error(err)
    })
  }

  return (
    <Card title={t['menu.list.searchTable']} extra={
      <div className={styles.spaces_2}>
        <Button type="primary" icon={<IconSearch />} onClick={fetchData}>
          搜索
        </Button>
        <Button type="primary" icon={<IconPlus />}
                onClick={() => {
                  setIsEdit(false)
                  setCurUser(
                    {}
                  )
                  setShowModal(true);
                }}>
          {t['searchTable.operations.add']}
        </Button>
      </div>
    }>
      <Table
        scroll={{
          x: 1800,
        }}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
        rowSelection={props.choose && {
          type: "checkbox",
          selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            console.log('onChange:', selectedRowKeys, selectedRows);
            setSelectedRowKeys(selectedRowKeys);
            props.onUpdate(selectedRowKeys)
          },
          onSelect: (selected, record, selectedRows) => {
            console.log('onSelect:', selected, record, selectedRows);
          }
        }}
      />
      {showModal && <Modal title={isEdit ? "修改订阅" : "添加订阅"}
             visible={showModal}
             hideCancel={true}
             footer={null}
             style={{width: "50%"}}
             onCancel={() => {setShowModal(false)}}
      >
        <Form ref={formRef} initialValues={curUser}>
          <Form.Item
            label="邮件"
            field="email"
            required
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="SMTP_Server"
            field="smtp_server"
            required
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="SMTP端口"
            field="smtp_port"
            required
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="账号名"
            field="username"
            required
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="密钥"
            field="password"
            required
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="是否默认"
            field='is_default'
            triggerPropName='checked'
            rules={[{ type: 'boolean', required: true }]}
          >
            <Switch />
          </Form.Item>
          <Button
            type="primary"
            onClick={async () => {
              if (formRef.current) {
                try {
                  await formRef.current.validate();
                  isEdit ? await handleSubmitUpdate() : await handleSubmit()
                  // Message.info('校验通过，提交成功！');
                } catch (_) {
                  console.error(formRef.current.getFieldsError());
                  Message.error('校验失败，请检查字段！');
                }
              }
            }}
            loading={loading}
            size="large"
          >
            {isEdit ? '保存修改' : '提交'}
          </Button>
        </Form>
      </Modal>}
      {
        showSendTempModal && <Modal
          title={"测试管理邮箱发送:" + curUser.email}
          visible={showSendTempModal} footer={null} onCancel={() => {setShowSendTempModal(false)}}>
          <Card>
            <Input onChange={(value) => {
              console.log(value);
              setTempEmail(value)
            }}></Input>
            <Button onClick={() => {
              sendTempEmail(curUser.id, tempEmail)
            }}>发送</Button>
          </Card>
        </Modal>
      }
    </Card>
  );
}

Subscription.prototype.setSelectedRowKeys = function(msg) {
  this.setSelectedRowKeys(msg);
};
export default Subscription;
